from rest_framework.response import Response
from rest_framework.views import APIView
from .models import FlowNode, FlowEdge
from .serializers import FlowNodeSerializer, FlowEdgeSerializer

class FlowDataAPI(APIView):
    def get(self, request):
        nodes = FlowNode.objects.all()
        edges = FlowEdge.objects.all()
        
        node_serializer = FlowNodeSerializer(nodes, many=True)
        edge_serializer = FlowEdgeSerializer(edges, many=True)
        
        # 需要把node_id字段改为id返回
        for node in node_serializer.data:
            node['id'] = node['node_id']
            del node['node_id']
        return Response({
            'nodes': node_serializer.data,
            'edges': edge_serializer.data
        })

    def post(self, request):
        # 清除旧数据
        FlowNode.objects.all().delete()
        FlowEdge.objects.all().delete()
        
        # 保存新节点
        nodes_data = request.data.get('nodes', [])
        print('nodes_data: ', nodes_data)
        for node in nodes_data:
            print('node: ', node, '\n')
            FlowNode.objects.create(
                node_id=node['node_id'],
                type=node['type'],
                position_x=node['position_x'],
                position_y=node['position_y'],
                data=node['data']
            )
        
        # 保存新边
        edges_data = request.data.get('edges', [])
        for edge in edges_data:
            FlowEdge.objects.create(
                edge_id=edge['edge_id'],
                source=edge['source'],
                target=edge['target'],
                source_handle=edge['source_handle'],
                target_handle=edge['target_handle']
            )
        
        return Response({'status':'success'}, status=201)